package com.shushan.login;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.huawei.android.hms.agent.HMSAgent;
import com.huawei.android.hms.agent.hwid.handler.SignInHandler;
import com.huawei.hms.support.api.hwid.SignInHuaweiId;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.db.ChildBeanDao;
import com.shushan.db.ChildBookDao;
import com.shushan.home.TabHomeActivity;
import com.shushan.login.bean.ChildBean;
import com.shushan.login.bean.ChildBookBean;
import com.shushan.login.bean.UserBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.setting.BookSelectActivity;
import com.shushan.setting.ChildSettingActivity;
import com.shushan.setting.ParentPswSetActivity;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.StringTools;
import com.shushan.util.ToolUtils;
import com.shushan.util.UmengEventUtil;
import com.shushan.web.ProtocolWebActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * @ClassName: LoginOrRegisterActivity
 * @Desciption: //登陆界面
 * @author: zhangshihao
 * @date: 2018-03-28
 */
public class LoginOrRegisterActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "LoginOrRegisterActivity";

    private Button btnGetMa, btnReadProtocol;
    private RelativeLayout huaweiLayout;
    private EditText etPhoneNum;
    private CheckBox checkBox;

    private String phoneNum;
    private boolean isLogout = false;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i(TAG, "onCreate()");

        isLogout = getIntent().getBooleanExtra("isLogout", false);

        setContentView(R.layout.activity_login2);

        ScreenManager sm = new ScreenManager();
        sm.setStatusBar(true, this);

        initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        isLogout = intent.getBooleanExtra("isLogout", false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.i(TAG, "onDestroy()");
    }

    private void initView() {
        huaweiLayout = findViewById(R.id.huawei_login_layout);
        huaweiLayout.setOnClickListener(this);
        if (getPackageName().equals(Constants.HUAWEI_PACKAGE_NAME)) {
            huaweiLayout.setVisibility(View.VISIBLE);
        }
        btnGetMa = findViewById(R.id.btn_get_ma);
        btnReadProtocol = findViewById(R.id.btn_read_protocol);
        etPhoneNum = findViewById(R.id.et_phone_num);
        checkBox = findViewById(R.id.checkbox);
        btnGetMa.setOnClickListener(this);
        btnReadProtocol.setOnClickListener(this);
        //默认填充手机号@{
        if (!TextUtils.isEmpty(SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY))) {
            Log.i(TAG, "shared mobile = " + SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));
            etPhoneNum.setText(SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY));
            etPhoneNum.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_black_fork, 0);
            etPhoneNum.setSelection(SharedPreferencesUtils.getStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY).length());
        } else {
            etPhoneNum.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);//隐藏右边图标
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        }
        //@}
        etPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count >= 1) {
                    etPhoneNum.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_black_fork, 0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etPhoneNum.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                Drawable drawable = etPhoneNum.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > etPhoneNum.getWidth()
                        - etPhoneNum.getPaddingRight()
                        - drawable.getIntrinsicWidth()) {
                    etPhoneNum.setText("");
                    etPhoneNum.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
                }
                return false;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_get_ma:
                checkPermissions();
                break;
            case R.id.btn_read_protocol:
                gotoProtocolWeb();
                break;
            case R.id.huawei_login_layout:
                onHuaweiLogin();
                break;
            default:
                break;
        }
    }

    /**
     * 检查app 权限
     */
    @SuppressLint("CheckResult")
    private void checkPermissions() {
        RxPermissions mRxPermissions = new RxPermissions(this);
        mRxPermissions.request(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe(permission -> {
            if (permission) {
                if (valide()) {
                    sendVerCode(phoneNum);
                }
            } else {
                showToast("请允许所有权限");
            }
        });
    }

    private void gotoProtocolWeb() {
        UrlParse urlParse = new UrlParse(UrlConst.BASE_URL)
                .appendRegion(UrlConst.USER_PROTOCOL);

        Intent intent = new Intent(this, ProtocolWebActivity.class);
        intent.putExtra("title", "用户协议");
        intent.putExtra("url", urlParse.toString());
        startActivityAllow(intent);
    }

    private boolean valide() {
        if (!checkBox.isChecked()) {
            showToast("请阅读并同意《用户协议》");
            return false;
        }

        phoneNum = etPhoneNum.getText().toString();
        if (!StringTools.isMobile(phoneNum)) {
            showToast("手机号输入有误");
            return false;
        }

        return true;
    }

    private void sendVerCode(final String mobile) {
        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.SEND_VER_CODE);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("debug", BuildConfig.DEBUG ? 1 : 0)
                .putValue("phone", mobile);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        Log.i(TAG, "onSuccess data=" + data);

                        String msgId = "";
                        String code = "";
                        try {
                            JSONObject jsonObject = new JSONObject(data);
                            msgId = jsonObject.optString("msgid", "");
                            code = jsonObject.optString("code", "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (TextUtils.isEmpty(msgId)) {
                            showToast("验证码ID为空");
                            return;
                        }

                        Intent intent = new Intent(LoginOrRegisterActivity.this, VerificationCodeActivity.class);
                        intent.putExtra("mobile", mobile);
                        intent.putExtra("msgId", msgId);
                        intent.putExtra("code", code);
                        startActivityAllow(intent);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (!isLogout && keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    private void onHuaweiLogin() {
        showWaitDialog();
        HMSAgent.Hwid.signIn(true, new SignInHandler() {
            @Override
            public void onResult(int rtnCode, SignInHuaweiId signInResult) {
                if (rtnCode == HMSAgent.AgentResultCode.HMSAGENT_SUCCESS && signInResult != null) {
                    //可以获取帐号的 openid，昵称，头像 at信息
                    Log.i(TAG, "登录成功=========");
                    Log.i(TAG, "昵称:" + signInResult.getDisplayName()
                            + "\nopenid:" + signInResult.getOpenId()
                            + "\naccessToken:" + signInResult.getAccessToken()
                            + "\n头像url:" + signInResult.getPhotoUrl());

                    String openId = signInResult.getOpenId();
                    if (TextUtils.isEmpty(openId)) {
                        showToast("openId 为空");
                        return;
                    } else {
                        getUserinfo(openId);
                    }
                } else {
                    Log.e(TAG, "登录---error: " + rtnCode);
                    showToast("华为登录验证失败");

                    dismissWaitDialog();
                }
            }
        });
    }

    private void getUserinfo(final String openId) {
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_THIRD_USER);
        urlParse.putValue("thirdid", openId);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<UserBean>() {

                    @Override
                    protected void onCommon() {
                        super.onCommon();

                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(UserBean userBean) {
                        if (userBean != null) {
                            if (TextUtils.isEmpty(userBean.phone)) {
                                Intent intent = new Intent(LoginOrRegisterActivity.this, MobileBindActivity.class);
                                intent.putExtra("openId", openId);
                                startActivityAllow(intent);
                            } else {
                                UmengEventUtil.onProfileSignIn(userBean.phone);

                                SharedPreferencesUtils.setBooleanDate(Constants.APP_NOT_FIRST_SHAREPREFERS_KEY, true);
                                SharedPreferencesUtils.setStringDate(Constants.LOGIN_MOBILE_SHAREPREFERS_KEY, userBean.phone);
                                shuShanApplication.setUserBean(userBean);

                                SharedPreferencesUtils.setStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY, userBean.password);

                                final PushAgent mPushAgent = PushAgent.getInstance(LoginOrRegisterActivity.this);
                                int currentChildId = shuShanApplication.getCurrentChildId();
                                if (currentChildId > 0) {
                                    mPushAgent.setAlias(currentChildId + "", Constants.UMENG_ALIAS_CHILD_ID_KEY, new UTrack.ICallBack() {
                                        @Override
                                        public void onMessage(boolean isSuccess, String message) {
                                            Log.i(TAG, "isSuccess=" + isSuccess + " message=" + message);
                                        }
                                    });
                                }

                                int useId = SharedPreferencesUtils.getIntDate(Constants.CURRENT_USE_ID_SHAREPREFERS_KEY);
                                if (useId > 0) {
                                    mPushAgent.setAlias(useId + "", Constants.UMENG_ALIAS_USE_ID_KEY, new UTrack.ICallBack() {
                                        @Override
                                        public void onMessage(boolean isSuccess, String message) {
                                            Log.i(TAG, "isSuccess=" + isSuccess + " message=" + message);
                                        }
                                    });
                                }

                                List<ChildBean> childList = userBean.getChildList();
                                if (childList.size() > 0) {
                                    new ChildBeanDao(shuShanApplication).dropAndAddList(childList);

                                    ChildBean childBean = childList.get(0);
                                    new ChildBookDao(shuShanApplication).clearTab();
                                    if (ToolUtils.isListEmpty(childBean.getBookBeanList())) {
                                        Intent intent = new Intent(LoginOrRegisterActivity.this, BookSelectActivity.class);
                                        intent.putExtra("gradeId", childBean.gradeId);
                                        intent.putExtra("semester", childBean.semester);
                                        intent.putExtra("firstTime", 1);
                                        startActivityAllow(intent);

                                    } else {
                                        List<ChildBookBean> bookBeanList = childBean.getBookBeanList();
                                        new ChildBookDao(shuShanApplication).addOrUpdateList(bookBeanList);

                                        if (!TextUtils.isEmpty(userBean.password)) {
                                            SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY, true);

                                            Intent intent = new Intent(LoginOrRegisterActivity.this, TabHomeActivity.class);
                                            intent.putExtra("firstTime", 1);
                                            startActivityAllow(intent);
                                        } else {
                                            Intent intent = new Intent(LoginOrRegisterActivity.this, ParentPswSetActivity.class);
                                            intent.putExtra("firstTime", 1);
                                            startActivityAllow(intent);
                                        }
                                    }


                                } else {
                                    new ChildBeanDao(shuShanApplication).clearTab();

                                    Intent intent = new Intent(LoginOrRegisterActivity.this, ChildSettingActivity.class);
                                    intent.putExtra("firstTime", 1);
                                    startActivityAllow(intent);
                                }
                            }

                        } else {
                            Intent intent = new Intent(LoginOrRegisterActivity.this, MobileBindActivity.class);
                            intent.putExtra("openId", openId);
                            startActivityAllow(intent);
                        }

                        onBackAction();
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNoMsgError(netRetBean);
                    }
                });
    }
}
